package sluentities;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.annotations.Embedded;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Transient;
import org.mongodb.morphia.query.Query;

import config.MongoDB;

@Entity(value = "rules", noClassnameStored = true)
public class GrammarRuleEntity {

    @Id
    protected ObjectId id;
    protected boolean ordered;
    @Embedded
    protected List<RuleEntryEntity> lists = new ArrayList<RuleEntryEntity>();

    @Transient
    private boolean varibleRule = false;

    public GrammarRuleEntity() {
        super();
    }

    public ObjectId getId() {
        return id;
    }

    public void setId(ObjectId id) {
		this.id = id;
	}

    public boolean getOrdered(){return ordered;}

    public void setOrdered(boolean ordered){this.ordered=ordered;}

    public List<RuleEntryEntity> getLists() {
        return lists;
    }

    public void setLists(List<RuleEntryEntity> lists) {
        this.lists = lists;
    }

    public GrammarRuleEntity(ObjectId id, List<RuleEntryEntity> lists) {
		super();
		this.id = id;
		this.lists = lists;
	}

    public boolean isVaribleRule() {
        return varibleRule;
    }

    public void setVaribleRule(boolean varibleRule) {
        this.varibleRule = varibleRule;
    }

    public GrammarRuleEntity remove(){

        Datastore mongoDatastore = MongoDB.instance().getDatabase();

        Query<NavigationEntity> q = mongoDatastore.createQuery(NavigationEntity.class).field("rules").equal(id);
        for (NavigationEntity navi:q){
            Iterator<GrammarRuleEntity> it = navi.getRules().iterator();
            while (it.hasNext()){
                if(it.next().getId().equals(id)){
                    it.remove();
                }
            }
            mongoDatastore.save(navi);
        }
        return this;
    }

}
